package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.ExcelUtils;
import com.settlement.system.listener.easyexcel.StoreImportListener;
import com.settlement.system.listener.easyexcel.UserImportListener;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.form.StoreForm;
import com.settlement.system.model.query.StorePageQuery;
import com.settlement.system.model.vo.StoreExportVO;
import com.settlement.system.model.vo.StoreVO;
import com.settlement.system.model.vo.SubjectsImportVo;
import com.settlement.system.model.vo.UserImportVO;
import com.settlement.system.service.SysStoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 店铺控制器
 */
@Tag(name = "店铺接口")
@RestController
@RequestMapping("/api/v1/store")
@RequiredArgsConstructor
public class SysStoreController {
    private final SysStoreService storeService;

    @Operation(summary = "店铺分页列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysStore> getStorePage(
            @ParameterObject StorePageQuery queryParams
    ) {
        Page<SysStore> result = storeService.getStorePage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "店铺列表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/list/storeKey/{storeKey}")
    public Result<List<StoreVO>> getListByStoreKey(
            @Parameter(description = "店铺Key") @PathVariable String storeKey
    ) {
        List<StoreVO> result = storeService.getListByStoreKey(storeKey);
        return Result.success(result);
    }

    @Operation(summary = "查询所有店铺", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/list/all")
    public Result<List<StoreVO>> getListByStoreKey() {
        List<StoreVO> result = storeService.getAllStore();
        return Result.success(result);
    }

    @Operation(summary = "保存店铺", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:store:save')")
    @PreventDuplicateSubmit
    public Result<?> saveStore(
            @RequestBody @Valid StoreForm storeForm
    ) {
        boolean result = storeService.saveStore(storeForm);
        return Result.judge(result);
    }

    @Operation(summary = "店铺表单数据", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{storeId}/form")
    public Result<SysStore> getStoreForm(
            @Parameter(description = "店铺ID") @PathVariable Long storeId
    ) {
        SysStore store = storeService.getStoreFormData(storeId);
        return Result.success(store);
    }

    @Operation(summary = "删除店铺", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:store:delete')")
    public Result<?> deleteStores(
            @Parameter(description = "店铺ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = storeService.deleteStores(ids);
        return Result.judge(result);
    }

    @Operation(summary = "禁用店铺", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/disable/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:store:disable')")
    public Result<?> disable(
            @Parameter(description = "店铺ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        storeService.disableStores(ids);
        return Result.success();
    }

    @Operation(summary = "启用店铺", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/enable/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:store:enable')")
    public Result<?> enable(
            @Parameter(description = "店铺ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        storeService.enableStores(ids);
        return Result.success();
    }

    @Operation(summary = "导出店铺", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    public void exportUsers(HttpServletResponse response) throws IOException {
        String fileName = "店铺列表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        StorePageQuery queryParams = new StorePageQuery();
        queryParams.setPageSize(200);
        Page<SysStore> storePage = storeService.getStorePage(queryParams);
        List<StoreExportVO> exportStoreList = new ArrayList<>();
        StoreExportVO vo;
        for (SysStore record : storePage.getRecords()) {
            vo = new StoreExportVO();
            BeanUtils.copyProperties(record, vo);
            exportStoreList.add(vo);
        }
        EasyExcel.write(response.getOutputStream(), StoreExportVO.class).sheet("店铺列表").doWrite(exportStoreList);
    }

    @Operation(summary = "导入店铺", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/_import")
    public Result<?> importUsers(MultipartFile file) throws IOException {
        StoreImportListener listener = new StoreImportListener();
        EasyExcelFactory.read(file.getInputStream(), StoreExportVO.class, listener).sheet(0).doRead();
        List<StoreExportVO> vos = listener.getVos();
        storeService.importStores(vos);
        return Result.success();
    }
}
